package at.ac.tuwien.sepm.s2011.e0208329.gui;

import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import at.ac.tuwien.sepm.s2011.e0208329.dao.*;
import at.ac.tuwien.sepm.s2011.e0208329.domain.*;

public class CreateGUI implements ActionListener{
	
	   ArrayList<Item> ItemList;
	   ItemDao itemDao;
	   JFrame appFrame;
	   JLabel jlbName, jlbType, jlbPrice, jlbStorage, jlbNr, jlbUpper, jlbLower;
	   JTextField jtfName, jtfType, jtfPrice, jtfStorage, jtfNr, jtfUpper, jtfLower;
	   JButton jbbSave, jbnDelete, jbnClear, jbnUpdate, jbnSearch,
			jbnShowALL, jbnBack, jbnExit;
	   String name, type;
	   int itemNr,price, storage,upper,lower;
	   Container cPane;

        //Constructor
        public CreateGUI(ItemDao id){
        	this.itemDao = id;
        }

		/*Create a frame, get its content pane and set layout*/

		//Arrange components on contentPane and set Action Listeners to each JButton
        public void arrangeComponents(){
        	appFrame = new JFrame("Item");
    		cPane = appFrame.getContentPane();
    		cPane.setLayout(new GridBagLayout());
    		
    		jlbName = new JLabel("Name");
    		jlbType = new JLabel("Type");
    		jlbPrice = new JLabel("Price");
    		jlbStorage = new JLabel("Storage");
    		jlbNr = new JLabel("ItemNr");
    		jlbUpper = new JLabel("UpperPrice");
    		jlbLower = new JLabel("LowerPrice");
    		jtfName = new JTextField(20);
    		jtfType = new JTextField(20);
    		jtfPrice = new JTextField(20);
    		jtfStorage = new JTextField(20);
    		jtfNr = new JTextField(10);
    		jtfUpper = new JTextField(10);
    		jtfLower = new JTextField(10);
    		jbbSave = new JButton("Save");
    		jbnDelete = new JButton("Delete");
    		jbnClear = new JButton("Clear");
    		jbnUpdate = new JButton("Update");
    		jbnSearch = new JButton("Search");
    		jbnShowALL = new JButton("ShowALL");
    		jbnBack = new JButton("");  // not in use, open for further edit
    		jbnExit = new JButton("Exit");
    		/*add all initialized components to the container*/
    		GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
    		gridBagConstraintsx01.gridx = 0;
    		gridBagConstraintsx01.gridy = 0;
    		gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5);
    		cPane.add(jlbName, gridBagConstraintsx01);
    		GridBagConstraints gridBagConstraintsx02 = new GridBagConstraints();
    		gridBagConstraintsx02.gridx = 1;
    		gridBagConstraintsx02.insets = new Insets(5, 5, 5, 5);
    		gridBagConstraintsx02.gridy = 0;
    		gridBagConstraintsx02.gridwidth = 2;
    		gridBagConstraintsx02.fill = GridBagConstraints.BOTH;
    		cPane.add(jtfName, gridBagConstraintsx02);
    		GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
    		gridBagConstraintsx03.gridx = 0;
    		gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5);
    		gridBagConstraintsx03.gridy = 1;
    		cPane.add(jlbType, gridBagConstraintsx03);
    		GridBagConstraints gridBagConstraintsx04 = new GridBagConstraints();
    		gridBagConstraintsx04.gridx = 1;
    		gridBagConstraintsx04.insets = new Insets(5, 5, 5, 5);
    		gridBagConstraintsx04.gridy = 1;
    		gridBagConstraintsx04.gridwidth = 2;
    		gridBagConstraintsx04.fill = GridBagConstraints.BOTH;
    		cPane.add(jtfType, gridBagConstraintsx04);
    		GridBagConstraints gridBagConstraintsx05 = new GridBagConstraints();
    		gridBagConstraintsx05.gridx = 0;
    		gridBagConstraintsx05.insets = new Insets(5, 5, 5, 5);
    		gridBagConstraintsx05.gridy = 2;
    		cPane.add(jlbPrice, gridBagConstraintsx05);
    		GridBagConstraints gridBagConstraintsx06 = new GridBagConstraints();
    		gridBagConstraintsx06.gridx = 1;
    		gridBagConstraintsx06.gridy = 2;
    		gridBagConstraintsx06.insets = new Insets(5, 5, 5, 5);
    		gridBagConstraintsx06.gridwidth = 2;
    		gridBagConstraintsx06.fill = GridBagConstraints.BOTH;
    		cPane.add(jtfPrice, gridBagConstraintsx06);
    		GridBagConstraints gridBagConstraintsx07 = new GridBagConstraints();
    		gridBagConstraintsx07.gridx = 0;
    		gridBagConstraintsx07.insets = new Insets(5, 5, 5, 5);
    		gridBagConstraintsx07.gridy = 3;
    		cPane.add(jlbStorage, gridBagConstraintsx07);
    		GridBagConstraints gridBagConstraintsx08 = new GridBagConstraints();
    		gridBagConstraintsx08.gridx = 1;
    		gridBagConstraintsx08.gridy = 3;
    		gridBagConstraintsx08.gridwidth = 2;
    		gridBagConstraintsx08.insets = new Insets(5, 5, 5, 5);
    		gridBagConstraintsx08.fill = GridBagConstraints.BOTH;
    		cPane.add(jtfStorage, gridBagConstraintsx08);
    		GridBagConstraints gridBagConstraintsx09 = new GridBagConstraints();
    		gridBagConstraintsx09.gridx = 0;
    		gridBagConstraintsx09.gridy = 4;
    		gridBagConstraintsx09.insets = new Insets(5, 5, 5, 5);
    		cPane.add(jbbSave, gridBagConstraintsx09);
    		GridBagConstraints gridBagConstraintsx10 = new GridBagConstraints();
    		gridBagConstraintsx10.gridx = 1;
    		gridBagConstraintsx10.gridy = 4;
    		gridBagConstraintsx10.insets = new Insets(5, 5, 5, 5);
    		cPane.add(jbnDelete, gridBagConstraintsx10);
    		GridBagConstraints gridBagConstraintsx11 = new GridBagConstraints();
    		gridBagConstraintsx11.gridx = 2;
    		gridBagConstraintsx11.gridy = 4;
    		gridBagConstraintsx11.insets = new Insets(5, 5, 5, 5);
    		cPane.add(jbnUpdate, gridBagConstraintsx11);
    		GridBagConstraints gridBagConstraintsx12 = new GridBagConstraints();
    		gridBagConstraintsx12.gridx = 0;
    		gridBagConstraintsx12.gridy = 5;
    		gridBagConstraintsx12.insets = new Insets(5, 5, 5, 5);
    		cPane.add(jbnBack, gridBagConstraintsx12);
    		GridBagConstraints gridBagConstraintsx13 = new GridBagConstraints();
    		gridBagConstraintsx13.gridx = 1;
    		gridBagConstraintsx13.gridy = 5;
    		gridBagConstraintsx13.insets = new Insets(5, 5, 5, 5);
    		cPane.add(jbnSearch, gridBagConstraintsx13);
    		GridBagConstraints gridBagConstraintsx14 = new GridBagConstraints();
    		gridBagConstraintsx14.gridx = 2;
    		gridBagConstraintsx14.gridy = 5;
    		gridBagConstraintsx14.insets = new Insets(5, 5, 5, 5);
    		cPane.add(jbnShowALL, gridBagConstraintsx14);
    		GridBagConstraints gridBagConstraintsx15 = new GridBagConstraints();
    		gridBagConstraintsx15.gridx = 1;
    		gridBagConstraintsx15.insets = new Insets(5, 5, 5, 5);
    		gridBagConstraintsx15.gridy = 6;
    		cPane.add(jbnClear, gridBagConstraintsx15);
    		GridBagConstraints gridBagConstraintsx16 = new GridBagConstraints();
    		gridBagConstraintsx16.gridx = 2;
    		gridBagConstraintsx16.gridy = 6;
    		gridBagConstraintsx16.insets = new Insets(5, 5, 5, 5);
    		cPane.add(jbnExit, gridBagConstraintsx16);
    		GridBagConstraints gridBagConstraintsx17 = new GridBagConstraints();
    		gridBagConstraintsx01.gridx = 0;
    		gridBagConstraintsx01.gridy = 1;
    		gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5);
    		cPane.add(jlbNr, gridBagConstraintsx17);
    		GridBagConstraints gridBagConstraintsx18 = new GridBagConstraints();
    		gridBagConstraintsx02.gridx = 1;
    		gridBagConstraintsx02.insets = new Insets(5, 5, 5, 5);
    		gridBagConstraintsx02.gridy = 1;
    		gridBagConstraintsx02.gridwidth = 2;
    		gridBagConstraintsx02.fill = GridBagConstraints.BOTH;
    		cPane.add(jtfNr, gridBagConstraintsx18);
    		GridBagConstraints gridBagConstraintsx19 = new GridBagConstraints();
    		gridBagConstraintsx19.gridx = 0;
    		gridBagConstraintsx19.gridy = 8;
    		gridBagConstraintsx19.insets = new Insets(5, 5, 5, 5);
    		cPane.add(jlbUpper, gridBagConstraintsx19);
    		GridBagConstraints gridBagConstraintsx20 = new GridBagConstraints();
    		gridBagConstraintsx20.gridx = 1;
    		gridBagConstraintsx20.insets = new Insets(5, 5, 5, 5);
    		gridBagConstraintsx20.gridy = 8;
    		gridBagConstraintsx20.gridwidth = 2;
    		gridBagConstraintsx20.fill = GridBagConstraints.BOTH;
    		cPane.add(jtfUpper, gridBagConstraintsx20);
    		GridBagConstraints gridBagConstraintsx21 = new GridBagConstraints();
    		gridBagConstraintsx21.gridx = 0;
    		gridBagConstraintsx21.gridy = 9;
    		gridBagConstraintsx21.insets = new Insets(5, 5, 5, 5);
    		cPane.add(jlbLower, gridBagConstraintsx21);
    		GridBagConstraints gridBagConstraintsx22 = new GridBagConstraints();
    		gridBagConstraintsx22.gridx = 1;
    		gridBagConstraintsx22.insets = new Insets(5, 5, 5, 5);
    		gridBagConstraintsx22.gridy = 9;
    		gridBagConstraintsx22.gridwidth = 2;
    		gridBagConstraintsx22.fill = GridBagConstraints.BOTH;
    		cPane.add(jtfLower, gridBagConstraintsx22);
    		
    		jbbSave.addActionListener(this); // detect the action on button
    		jbnClear.addActionListener(this);
    		jbnExit.addActionListener(this);
    		jbnDelete.addActionListener(this);
    		jbnShowALL.addActionListener(this);
    		jbnSearch.addActionListener(this); 
    		jbnUpdate.addActionListener(this);     		/* 		
    		jbnBack.addActionListener(this);
    		*/
    		appFrame.setSize(500,500);
    		appFrame.setResizable(true);
    		appFrame.setVisible(true);
        }
        
    	public void actionPerformed(ActionEvent e) {
    		if (e.getSource() == jbbSave) {
    			saveItem();
    		} else if (e.getSource() == jbnClear) {
    			clear();
    		} else if (e.getSource() == jbnExit) {
    			System.exit(0);
    		} else if (e.getSource() == jbnDelete) {
    			delete();
    			clear();
    		}else if (e.getSource() == jbnShowALL) {  			
    			try{
    				queryAll();
    			}catch (Exception ee){
    				System.out.print("Error at CreateGUI.actionPerformed()/itemDao.queryAll()");
    			}
    		} else if (e.getSource() == jbnSearch) {
    			queryBy();
    		} else if (e.getSource() == jbnUpdate) {
    			update();
    		 }
    	}
    	
    	//Method to clear the Text field
    	public void clear() {
    		jtfName.setText("");
    		jtfPrice.setText("");
    		jtfType.setText("");
    		jtfStorage.setText("");
    		jtfNr.setText("");
    		jtfUpper.setText("");
    		jtfLower.setText("");
    	}
    	
    	//Method for insert an Item, bounded with ItemDao.insert()
    	public void saveItem(){
    		boolean flag = true; // only when flag=true, the entered Text
    		                     // would be saved
    		name = jtfName.getText();
    		if (name.equals("")) {
    			flag = false;
    			JOptionPane.showMessageDialog(null,"Please enter Item name.");
    		}
    		try {
    			price = Integer.parseInt("" + jtfPrice.getText());
    		} catch (Exception e) {
    			//when the input is a String, cause to Exception
    			flag = false;
                JOptionPane.showMessageDialog(null, "Please enter Price(Integer)");
    		}
    		type = jtfType.getText();
    		if (type.equals("")) {
    			flag = false;
    			JOptionPane.showMessageDialog(null,"Please enter Item type.");
    		}
    		try {
    			storage = Integer.parseInt("" + jtfStorage.getText());
    		} catch (Exception e) {
    			//when the input is a String, cause to Exception
    			flag = false;
    			JOptionPane.showMessageDialog(null, "Please enter Storage(Integer)");
    		}
            //check the flag, if true, made action
    		if(flag==true){
    			//create a Item object and pass it to itemDAO to insert it
    			Item item = new Item();
    			item.setItem(1,name, price, type, storage);
    			try{
    				itemDao.insert(item);
    			}catch (Exception e){
    				System.out.print("Error at CreateGUI.saveItem()/itemDao.insert()");
    			}
    			JOptionPane.showMessageDialog(null, "Item Saved");
    			clear();
    		}
    	}
    	
    	// update an Item of entered ItemNr with entered Price and/or Storage
    	public void update(){
    		boolean flag = true; // only when flag=true, the entered Text
    		                     // would be saved
    		boolean flag1 = true;  // action flag for update-price 
    		boolean flag2 = true;  // action flag for update-Storage
    		try {  //get ItemNr
    			itemNr = Integer.parseInt("" + jtfNr.getText());
    		} catch (Exception e) {
    			//when the input is empty or a String, cause to Exception
    			flag = false;
                JOptionPane.showMessageDialog(null, "Please enter ItemNr(Integer)" +
                		"to update");
    		}
    		try {  //get Price
    			price = Integer.parseInt("" + jtfPrice.getText());
    		} catch (Exception e) {
    			//when the input is a String, cause to Exception
    			flag1 = false;
    			if(!jtfPrice.getText().equals("")){//notice to enter correct info
                    JOptionPane.showMessageDialog(null, "Please enter Price(Integer)");
    			}
    		}
    		try {  // get Storage
    			storage = Integer.parseInt("" + jtfStorage.getText());
    		} catch (Exception e) {
    			//when the input is a String, cause to Exception
    			flag2 = false;
    			if(!jtfStorage.getText().equals("")){ //notice to enter correct info
        			JOptionPane.showMessageDialog(null, "Please enter Storage(Integer)");
    			}
    		}
             
    		if((flag==true)&&((flag1==true)||(flag2==true))){
    			flag=true; //only when at least one update option is entered, will perform update
    		}else{
    			flag=false;
    		}
            //check the flag, if true, made action
    		if(flag==true){
    			if(flag1==true){
        			try{
        				itemDao.updatePrice(itemNr,price);
        			}catch (Exception e){
        				System.out.print("Error at CreateGUI.update()/itemDao.updatePrice()");
        			}
    			}
    			if(flag2==true){
        			try{
        				itemDao.updateStorage(itemNr,storage);
        			}catch (Exception e){
        				System.out.print("Error at CreateGUI.update()/itemDao.updateStorage()");
        			}    			
    			}
    			JOptionPane.showMessageDialog(null, "Item Updated");
    			clear();
    		}else{
    			JOptionPane.showMessageDialog(null, "no Item Updated");
    		}
    	}
    	
    	//delete Item (actually tagged) with entered ItemNr
    	public void delete() {
    		boolean flag = true;
    		try {
    			itemNr = Integer.parseInt("" + jtfNr.getText());
    		} catch (Exception e) {
    			//when the input is empty or a String, cause to Exception
    			flag = false;
                JOptionPane.showMessageDialog(null, "Please enter ItemNr(Integer)" +
                		"to delete");
    		}
    		if(flag==true){
    			//remove Item of the given Nr from the database
    			try{
    				this.itemDao.delete(itemNr);
    			}catch (Exception e){
    				System.out.print("Error at CreateGUI.delete()/itemDao.delete()");
    			}
    			JOptionPane.showMessageDialog(null, "1 Record deleted.");
    		}
    	}
    	
    	// show all not tagged Items from Database
        public void queryAll() throws Exception{
        	List<Item> listIt2 = new ArrayList<Item>(); //temporary List to save Items of Database
    	    listIt2 = this.itemDao.queryAll(); 
        	report(listIt2,"All Items");
        }
        
        
        //Method to generate a Report for Search-Results
        public void queryBy(){
    		boolean flag = true; // only when flag=true, the search 
                                 // would be performed
            name = jtfName.getText();
            type = jtfType.getText();

            if (jtfUpper.getText().equals("")){
            	upper = 999999;  // if upper price not entered, give it a default price
            }else{
                try {
                    upper = Integer.parseInt("" + jtfUpper.getText());
                } catch (Exception e) {
                   //when the input is a String, cause to Exception
                    flag = false;
                    JOptionPane.showMessageDialog(null, "Please enter UpperPrice(Integer)");
                }
            }
            if (jtfLower.getText().equals("")){
            	lower = 0;  // if lower price not entered, give it a default price
            }else{
                try {
                    lower = Integer.parseInt("" + jtfLower.getText());
                 } catch (Exception e) {
                   //when the input is a String, cause to Exception
                    flag = false;
                    JOptionPane.showMessageDialog(null, "Please enter LowerPrice(Integer)");
                 }          	
            }
            if(flag==true) {
            	//if flag true, pass the Item list to listIt1
            	List<Item> listIt1 = new ArrayList<Item>();
        	    try {
					listIt1 = itemDao.queryBy(name,type,upper,lower);
				} catch (Exception e) {
					System.out.print("Error at CreateGUI.queryBy()/itemDao.queryBy()");
				}
            	report(listIt1,"Search Result");
            	clear();
            }
        }
    	
        
        //Method to generate Report-List of Items in a pop up window
        public static void report(List<Item> li,String s){
        	Iterator<Item> itli = li.iterator();
        	JFrame appFrame1 = new JFrame(s);
      		
      		appFrame1.setVisible(true);
      		
        	JTextArea t1;
        	String str = "";
        	while(itli.hasNext()){
        		str = str + itli.next().report();
        	}
        	t1 = new JTextArea(str,10,15);
        	t1.setEditable(false);
        	Container c = appFrame1.getContentPane();
        	//JButton jbbClear;
        	JLabel jlbTitle;
        	jlbTitle= new JLabel("ItemNr, Name, Price, Type, Storage");
        	c.add(jlbTitle,"North");
        	c.add(new JScrollPane(t1),"Center");
        	appFrame1.setSize(270,600);
        	
        }
}
